from typing import *
from math import inf
class Solution:
    def minFallingPathSum(self, grid: List[List[int]]) -> int:
        n = len(grid)
        if n == 1:
            return grid[0][0]

        def f(arr):
            a = 0 if arr[0] < arr[1] else 1
            b = 0 if arr[0] > arr[1] else 1
            for i in range(2,n):
                num = arr[i]
                if num < arr[a]:
                    b = a
                    a = i
                elif num < arr[b]:
                    b = i
            return a,b
        for i in range(1,n):
            a,b = f(grid[i - 1])
            for j in range(n):
                grid[i][j] +=  grid[i - 1][b] if j == a else grid[i - 1][a]
        return min(grid[n-1])
                    